import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 解决导航栏或者底部导航tabBar中的vue-router在3.0版本以上频繁点击菜单报错的问题。
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/', redirect: "/login" },
  { path: '/login', name: 'Login', meta: { name: '登录' }, component: () => import('../views/Login.vue') },

  { path: '*', name: 'NotFound', meta: { name: '无法访问' }, component: () => import('../views/404.vue') },


  {
    path: '/admin',
    name: 'admin',
    redirect: '/admin/order',
    component: () => import('../views/AdminSide'),
    children: [
      { path: '/admin/order', name: 'order', meta: { name: '订单统计' }, component: () => import('../views/admin/order') },
      { path: '/admin/userTrack', name: 'userTrack', meta: { name: '用户痕迹跟踪' }, component: () => import('../views/admin/userTrack') },
      { path: '/admin/user', name: 'user', meta: { name: '用户管理' }, component: () => import('../views/admin/user') },
    ]

  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// router.beforeEach((to, from, next) => {
//   //判断用户是从哪个路由过来的

//   //也可以判断用户要去哪个路由
//   if (to.path === '/login') {
//     next()
//   } else {
//     let token = localStorage.getItem('token')
//     token ? next() : next('/login')
//   }
//   console.log("from:", from.name)
//   console.log("to:", to.name);
//   //return false;终止页面跳转
//   //if(to.name==='detail'){
//   // return {name:'about'};//指定跳转到某一个页面
//   //}

// })

// 注：不需要前台的项目，可以注释掉该路由守卫
// 路由守卫
router.beforeEach((to, from, next) => {
  let user = JSON.parse(localStorage.getItem("xm-user") || '{}');
  if (to.path === '/') {
    if (user.role) {
      if (user.role === 'USER') {
        next('/front/home')
      } else {
        next('/home')
      }
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
